from django.db import models
from libs.mixins import ModelMixin
from libs.utils import human_time


class CourseCategory(models.Model, ModelMixin):
    """课程大类"""
    school = models.CharField("所属学校", max_length=100, null=True)
    name = models.CharField("课程大类", max_length=50)
    sort_id = models.IntegerField("排序", default=0)
    add_time = models.CharField("创建时间", max_length=20, default=human_time)
    update_time = models.CharField("更新时间", max_length=20, default=human_time)
    is_delete = models.BooleanField("是否删除", default=False)

    def __repr__(self):
        return '<CourseCategory %r>' % self.name

    class Meta:
        db_table = 'course_category'
        ordering = ('sort_id',)
        verbose_name = '课程大类'
        verbose_name_plural = '课程类别管理'


class Course(models.Model, ModelMixin):
    """课程信息"""
    category = models.ForeignKey(CourseCategory, on_delete=models.PROTECT, verbose_name="课程大类")
    name = models.CharField("课程名称", max_length=100)
    year = models.IntegerField("课程年份")
    price = models.DecimalField("课程价格", max_digits=8, decimal_places=2)
    description = models.TextField("课程描述", null=True, blank=True)
    start_date = models.DateField("开始日期")
    end_date = models.DateField("结束日期")
    status = models.CharField("课程状态", max_length=20, choices=(
        ('pending', '未开始'),
        ('in_progress', '进行中'), 
        ('finished', '已结束')
    ), default='pending')
    add_time = models.CharField("创建时间", max_length=20, default=human_time)
    update_time = models.CharField("更新时间", max_length=20, default=human_time)
    is_delete = models.BooleanField("是否删除", default=False)

    def to_dict(self, selects=None):
        data = super().to_dict(selects=selects)
        data['category_info'] = self.category.to_dict() if self.category else {}
        data['status_alias'] = self.get_status_display()
        return data

    def __repr__(self):
        return '<Course %r>' % self.name

    class Meta:
        db_table = 'course'
        ordering = ('-id',)
        verbose_name = '课程'
        verbose_name_plural = '课程管理'
